<?php

namespace app\api\controller;

use think\Controller;
use think\Db;
use app\api\model\News;
use app\api\model\Common;
use app\api\model\Form;

class Account extends Index
{
    //修改密码
    public function edit_pwd()
    {
        $where['uid'] = input('get.uid');
        $old_pwd = input('get.old_pwd');
        $new_pwd = input('get.new_pwd');
        $news = new News('user');
        $res = $news->check_name($where);
        $old_rand = $res['rand'];
        $common = new Common();
        $old_password = $common->change_pwd($old_pwd, $old_rand);
        if ($old_password == $res['password']) {
            $new_rand = $common->GetRandStr();
            $new_password = $common->change_pwd($new_pwd, $new_rand);
            $data['password'] = $new_password;
            $data['rand'] = $new_rand;
            $flag = Db::name('user')->where($where)->update($data);
            if ($flag) {
                action_log_index('修改密码', 'log_ment', 1);
                $this->_jsonp('200', '修改成功', null);
            } else {
                action_log_index('修改密码失败', 'log_ment');
                $this->_jsonp('1001', '修改失败', null); //原密码错误
            }
        } else {
            $this->_jsonp('1000', '密码错误', null); //原密码错误
        }

    }

    //验证手机邮箱是否注册
    public function check_email()
    {
        $status = trim(input('get.status'));
        $news = new News('user');
        if ($status == 1) {
            $where['email'] = input('get.email');
            $name = '邮箱';
        } else {
            $where['phone'] = trim(input('get.phone'));
            $name = '手机';
        }
        $res = $news->check_name($where);
        if ($res) {
            $this->_jsonp('1000', $name . '已被绑定', null);
        } else {
            $this->_jsonp('200', $name . '未绑定', null);
        }
    }

    /* 验证验证码
      * message:邮箱或是手机号
      * code:验证码
      * uid:用户id
     * type:1表示邮箱，2表示手机
     * model:1表示绑定手机号，2表示修改手机号
      * */
    public function check_sms()
    {
        if (empty($_GET['message']) || empty($_GET['code']) || empty($_GET['uid']) || empty($_GET['type'])) {
            $this->_jsonp("1003", "参数错误", null);
        }
        $message = (string)$_GET['message'];
        $map['uid'] = $_GET['uid'];
        $code = $_GET['code'];
        $where = array(
            "message" => $message,
            "code" => $code,
            "status" => 1,
        );
        //验证是否属于原手机号主人
        //model为2表示是修改手机号，为1表示绑定
        if ($_GET['type'] == 2 && $_GET['model'] == 2) {
            $old_phone = $_GET['old_phone'];
            $users = new News('user');
            $old = $users->check_name($map);
            if ($old_phone != $old['phone']) {
                $this->_jsonp("1004", "非原手机号", null);
            }
        }
        $zgh_sms_code = new News('sms_code');
        // dump($zgh_sms_code);exit;
        $field = 'id,time,code,is_status';
        $info = $zgh_sms_code->check_name($where, $field);
        if (!$info) {
            $this->_jsonp("1000", "验证码错误", null);
        }
        // $_time = time() - 180;
        $_time = time() - 100000;//测试，上线时删除此条
        if ($_time > $info['time'] || $info['is_status'] == 1) {
            $this->_jsonp("1001", "验证码失效", null);
        }
        // M("sms_code") -> startTrans();
        $data['is_status'] = 1;
        $u_where['id'] = $info['id'];
        if ($_GET['type'] == 1) {
            $mes['email'] = $message;
        } else {
            $mes['phone'] = $message;
        }
        //$_info = 1; //测试，上线时删除此条，并去掉上一条注释
        $flag = 1;
        Db::startTrans();
        try {
            $_info = Db::name("sms_code")->where(array("id" => $info['id']))->update(array("is_status" => 1));
            Db::name("user")->where($map)->update($mes);
            Db::commit();
            $flag = 2;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        if ($flag == 2) {
            action_log_index('绑定手机号', 'log_ment', 1);
            $this->_jsonp('200', '绑定成功', null);
        } else {
            action_log_index('绑定手机号失败', 'log_ment');
            $this->_jsonp('1000', '绑定失败', null);
        }

    }

    /*
      *是否设置了密码
      *
      * */
    public function check_person()
    {
        $id = input('get.uid');
        $where['uid'] = $id;
        $news = new News('user');
        $res = $news->check_name($where);
        if ($res['alipay']) {
            $this->_jsonp('200', '已设置密码', null);
        } else {
            $this->_jsonp('1000', '还未设置', null);
        }
    }

    /*
      *设置账户密码
      *
      * */
    public function check_code()
    {
        //核对账户和登录密码
        $id = input('get.uid');
        $password = input('get.password');
        $username = input('get.username');
        $code = input('get.code');
        $where['uid'] = $id;
        $news = new News('user');
        $common = new Common();
        $res = $news->check_name($where);
        $p = $common->change_pwd($password, $res['rand']);
        if ($p != $res['password']) {
            $this->_jsonp('1000', '登录密码不正确', null);
        }
		if ($username == $res['username']) {
			$data['alipay_rand'] = $common->GetRandStr();
			$data['code'] = $common->change_pwd($code, $data['alipay_rand']);
			$data['username'] = $username;
			$flag = Db::name('user')->where($where)->update($data);
			if ($flag) {
				action_log_index('设置手机号', 'log_ment', 1);
				$this->_jsonp('200', '设置成功', null);
			} else {
				action_log_index('设置手机号失败', 'log_ment');
				$this->_jsonp('1000', '设置失败', null);
			}
		} else {
			$this->_jsonp('1000', '用户名错误', null);
		}
        

    }

    /*
      *资讯收藏列表
      *
      * */
    public function news_list()
    {
        $where['a.uid'] = input('get.uid');
        $where['a.static'] = 0;
        $where['a.type'] = 3;
        $number = (isset($_GET['number']) && !empty($_GET['number'])) ? $_GET['number'] : 3;
        $page = (isset($_GET['page']) && !empty($_GET['page'])) ? $_GET['page'] : 1;
        $where['w.status'] = 1;
        $alias = 'a';
        $news_list = new News('collect');
        $count = Db::name('collect')->alias($alias)->join('zgh_government_work w','w.id=a.mid')->where($where)->count();
        // dump($count);exit;
        //调用模型
        $condition = 'w.id=a.mid';
        $data = Db::name('collect')->alias($alias)->join('zgh_government_work w','w.id=a.mid')->where($where)
            ->field('a.id as c_id,a.time as c_time,w.*')
            ->order('a.time desc')
            ->limit($number)
            ->page($page)->select();
        //分页
        $Page = $news_list->page($count, $number);
        $render = $Page->render;
        $res['count'] = $count;
        $res['data'] = $data;
        $res['render'] = $render;
        if (isset($data) || !empty($data)) {
            $this->_jsonp('200', '新闻列表数据获取成功', $res);
        } else {
            $this->_jsonp('1000', '暂未收藏新闻资讯', null);
        }
    }
    /*
     *资讯取消收藏
     *
     * */
    /**前台取消收藏**/
    public function cancel_collect()
    {
        $id = input('get.id');//收藏的id
        $where['id']=array('IN',$id);
        $new=Db::name('collect')->where($where)->column('mid');
        $map['id']=array('IN',implode(',',$new));
        $flag=Db::name("government_work")->where($map)->setDec('collect');
        $data['static']=1;
        $like_add = Db::name("collect")->where($where)->update($data);
		
        if ($like_add !== false) {
            action_log_index('咨询取消收藏', 'log_ment', 1);
            $this->_jsonp('200', '取消收藏成功', null);
        } else {
            action_log_index('咨询取消收藏失败', 'log_ment');
            $this->_jsonp('1000', '取消收藏失败', null);
        }
    }

    /**视频收藏列表*/
    public function course_list()
    {
        $where['a.uid'] = input('get.uid');
        $where['a.static'] = 0;
        $where['a.type'] = 4;
        $number = (isset($_GET['number']) && !empty($_GET['number'])) ? $_GET['number'] : 3;
        $page = (isset($_GET['page']) && !empty($_GET['page'])) ? $_GET['page'] : 1;
        $where['b.status'] = 1;
        $alias = 'a';
        $news_list = new News('collect');
        $count = Db::name('collect')->alias($alias)->join('zgh_video b','b.id=a.mid')->where($where)->count();
        // dump($count);exit;
        //调用模型
        $data = Db::name('collect')->alias($alias)->join('zgh_video b','b.id=a.mid')
            ->join('zgh_video_list l','l.id=b.l_id')
            ->where($where)
            ->field('a.id as c_id,a.time as c_time,b.*,l.pic')
            ->order('a.time desc')
            ->limit($number)
            ->page($page)->select();
        //分页
        $Page = $news_list->page($count, $number);
        $render = $Page->render;
        $res['count'] = $count;
        $res['data'] = $data;
        $res['render'] = $render;
        if (isset($data) || !empty($data)) {
            $this->_jsonp('200', '视频列表数据获取成功', $res);
        } else {
            $this->_jsonp('1000', '暂未收藏视频资讯', null);
        }
    }

    //视频取消收藏
    public function cancel_video()
    {
        $id = input('get.id');//收藏的id
        $where['id']=array('IN',$id);
        $new=Db::name('collect')->where($where)->column('mid');
        $map['id']=array('IN',implode(',',$new));
        $list=Db::name('video')->where($map)->column('l_id');
        $map2['id']=array('IN',implode(',',$list));
        $data['static']=1;
        $like_add = Db::name("collect")->where($where)->update($data);
         Db::name("video")->where($map)->setDec('v_collect');
         Db::name("video_list")->where($map2)->setDec('collect');
        if ($like_add !== false) {
            action_log_index('视频取消收藏', 'log_ment', 1);
            $this->_jsonp('200', '取消收藏成功', null);
        } else {
            action_log_index('视频取消收藏', 'log_ment');
            $this->_jsonp('1000', '取消收藏失败', null);
        }
    }

    //商品列表trade
    public function trade_list()
    {
        $where['a.uid'] = input('get.uid');
        $where['a.static'] = 0;
        $where['a.type'] = 1;
        $number = (isset($_GET['number']) && !empty($_GET['number'])) ? $_GET['number'] : 3;
        $page = (isset($_GET['page']) && !empty($_GET['page'])) ? $_GET['page'] : 1;
        $where['w.is_show'] = 1;
        $condition1 = 'w.category_id=m.id';
        $type1 = 'zgh_market_trading_category m';
        $type2 = 'zgh_shop_information i';
        $condition2 = 'w.name=i.id';
        $type3 = 'zgh_market_trading_cid t';
        $condition3 = 'w.c_id=t.id';
        $fields = "a.id as collect_id,a.time as c_time,w.*,i.name as shop_name,t.trading_name,m.market_name";
        $news_list = new News('market_trading');
        $count = Db::name('collect')->alias('a')
            ->field($fields)
            ->join('zgh_market_trading w','a.mid=w.id','left')
            ->where($where)
            ->count();
        $data = Db::name('collect')->alias('a')
            ->field($fields)
            ->join('zgh_market_trading w','a.mid=w.id','left')
            ->join($type1,$condition1,'left')
            ->join($type2,$condition2,'left')
            ->join($type3,$condition3,'left')
            ->where($where)
            ->order('a.time desc')
            ->limit($number)
            ->page($page)->select();
		
        $mark = Db::name('collect')->alias('a')
                    ->join('zgh_market_trading w','a.mid=w.id','left')
                    ->field('w.name as shop,count(w.name) as number,i.name as shop_name')
                    ->join($type1,$condition1,'left')
                    ->join($type2,$condition2,'left')
                    ->join($type3,$condition3,'left')
                    ->where($where)
					->order('a.time desc')
                    ->group('w.name')
                    ->select();
		$shows=array();
		foreach($data as $k=>$v){
			foreach($mark as $key=>$val){           
                if($v['name']==$val['shop']){
                    $shows[$key]=$val;
                }
            }
        }
        $res['shop_id']=array_merge($shows);
        //分页
        $Page = $news_list->page($count, $number);
        $render = $Page->render;
        $res['count'] = $count;
        $res['data'] = $data;
        $res['render'] = $render;
        if (isset($data) || !empty($data)) {
            $this->_jsonp('200', '交易商品收藏列表数据获取成功', $res);
        } else {
            $this->_jsonp('1000', '交易商品收藏数据获取失败', null);
        }
    }

    //服务商品列表service
    public function service_list()
    {
        $where['a.uid'] = input('get.uid');
        $where['a.static'] = 0;
        $where['a.type'] = 2;
        $number = (isset($_GET['number']) && !empty($_GET['number'])) ? $_GET['number'] : 3;
        $page = (isset($_GET['page']) && !empty($_GET['page'])) ? $_GET['page'] : 1;
        $where['w.state'] = 1;
        $where['w.status'] = 1;
        $condition1 = 'w.type=m.id';
        $type1 = 'zgh_service_type m';
        $type2 = 'zgh_shop_information i';
        $condition2 = 'w.s_id=i.id';
        $fields = "a.id as collect_id,a.time as c_time,w.*,i.name as shop_name,m.t_name";
        $count = Db::name('collect')->alias('a')
            ->join('zgh_service_market w','a.mid=w.id','left')
            ->where($where)
            ->count();
        $data = Db::name('collect')->alias('a')
            ->field($fields)
            ->join('zgh_service_market w','a.mid=w.id','left')
            ->join($type1,$condition1,'left')
            ->join($type2,$condition2,'left')
            ->where($where)
            ->order('a.time desc')
            ->limit($number)
            ->page($page)->select();
        $res['shop_id'] = Db::name('collect')->alias('a')
            ->join('zgh_service_market w','a.mid=w.id','left')
            ->field('w.s_id as shop,count(w.s_id) as number,i.name as shop_name')
            ->join($type1,$condition1,'left')
            ->join($type2,$condition2,'left')
            ->where($where)
			->order('a.time desc')
            ->limit($number)
            ->page($page)
            ->group('w.s_id')
            ->select();
        //分页
        $news_list=new News();
        $Page = $news_list->page($count, $number);
        $render = $Page->render;
        $res['count'] = $count;
        $res['data'] = $data;
        $res['render'] = $render;
        if (isset($data) || !empty($data)) {
            $this->_jsonp('200', '服务商品收藏列表数据获取成功', $res);
        } else {
            $this->_jsonp('1000', '服务商品收藏数据获取失败', null);
        }
    }

    //商品取消收藏
    public function cancel_goods()
    {
        $id = input('get.id');//收藏的id
        $where['id']=array('IN',$id);
        $type = input('get.type');
        if ($type == 1) {

            $basename = 'market_trading';//收藏所在的表类型
        } else {
            $basename = 'service_market';
        }
        $new=Db::name('collect')->where($where)->column('mid');
		
        $data1['static']=1;
        $map['id']=array('IN',implode(',',$new));
        $like_add = Db::name("collect")->where($where)->update($data1);
        Db::name($basename)->where($map)->setDec('collect');
        if ($like_add !== false) {
            action_log_index('商品取消收藏', 'log_ment', 1);
            $this->_jsonp('200', '取消收藏成功', null);
        } else {
            action_log_index('商品取消收藏', 'log_ment');
            $this->_jsonp('1000', '取消收藏失败', null);
        }
    }

    //个人中心申请退款
    public function refund_add()
    {
        $data['uid'] = input('post.uid');
        $data['order'] = input('post.order');//订单号
        $data['problem'] = htmlspecialchars(trim(input('post.problem')));
        $data['nick'] = htmlspecialchars(trim(input('post.nick')));
        $data['static'] = 1;
        $data['phone'] = htmlspecialchars(trim(input('post.phone')));
        $data['time'] = time();
        $where['id'] = input('post.id');
        $old_order = Db::name('orders')->where($where)->find();
        $data['money'] = $old_order['money'];
        if ($old_order['statuc'] == 1) {
            $this->json('1000', '网络错误', null);
        }
        $data1['statuc'] = 10;
        $data1['status'] = 12;
        $data1['static'] = 2;
        $data2['order_num'] = $where['id'];
        $data2['order_status'] = 10;
        $arr['status'] = $old_order['status'];
		$arr['statuc'] = $old_order['statuc'];
		$arr['static'] = $old_order['static'];
        $arr['msg'] = $data['problem'];
        $data2['order_msg'] = json_encode($arr);
        $data2['time'] = time();
        $standard = 1;
        //启动事务
        Db::startTrans();
        try {
            Db::name('orders')->where($where)->update($data1);
            Db::name('refund')->insert($data);
            Db::name('order_msg')->insert($data2);
            Db::commit();
            $standard = 2;
        } catch (\Exception $e) {
            Db::rollback();
        }
        if ($standard == 2) {
            action_log_index('申请退款', 'log_ment', 1);
            $this->json('200', '提交成功', null);
        } else {
            action_log_index('申请退款', 'log_ment');
            $this->json('1000', '提交失败', null);
        }
    }

    //店铺中心确认退款
    public function confirm_refund()
    {
        $id = input('get.id');
		$where1['id']=$id;
		$show_order=Db::name('orders')->where($where1)->value('order');
        $show['order'] = $show_order;
        $status = input('get.status');
        $show_res = Db::name('refund')->where($show)->distinct(true)->order('id desc')->find();
        $refund['id'] = $show_res['id'];
        if ($status == 1) {
            //确认退款
            $data1['status'] = 13;
            $data2['order_num'] = $id;
            $data2['order_status'] = 13;
            $data2['order_msg'] = '买家同意退款';
            $data2['time'] = time();
            $data3['static'] = 2;
        } else if ($status == 2) {
            //取消退款
            $where['order_num'] = $id;
            $data3['result'] = htmlspecialchars(trim(input('get.result')));
            $res = Db::name('order_msg')->where($where)->distinct(true)->order('id desc')->find();
            if ($res['order_status'] == 10) {
                $log = json_decode($res['order_msg'], true);
                $new_static = 15;
                $data1['statuc'] = $log['statuc'];
                $data1['status'] =  $log['status'];
				$data1['static'] =  $log['static'];
                $data2['order_num'] = $id;
                $data2['order_status'] = $new_static;
                $data2['order_msg'] = '卖家不同意退款,回到原状态';
                $data2['time'] = time();
                $data3['static'] = 4;//表示已驳回
            } else {
                $this->_jsonp('1000', '网络错误', null);
            }
        }
		$data2['type'] = 2;
        $map['id'] = $id;
        $standard = 1;
	
        //启动事务
        Db::startTrans();
        try {
            Db::name('orders')->where($map)->update($data1);
            Db::name('refund')->where($refund)->update($data3);
            Db::name('order_msg')->insert($data2);
            Db::commit();
            $standard = 2;
        } catch (\Exception $e) {
            Db::rollback();
        }
        if ($standard == 2) {
            action_log_index('卖家确认退款', 'log_ment', 1);
            $this->_jsonp('200', '提交成功', null);
        } else {
            action_log_index('卖家确认退款', 'log_ment');
            $this->_jsonp('1000', '提交失败', null);
        }
    }

    //退款列表
    public function refund_list()
    {
        $number = (isset($_GET['number']) && !empty($_GET['number'])) ? $_GET['number'] : 5;
        $page = (isset($_GET['page']) && !empty($_GET['page'])) ? $_GET['page'] : 1;
        $static = (isset($_GET['static']) && !empty($_GET['static'])) ? $_GET['static'] : array('neq', 0);
        $show['uid'] = input('get.uid');
        $show['static'] = $static;
		$map['uid']= input('get.uid');
        $count = Db::name('refund')->where($show)->count();
        $res = Db::name('refund')->where($show)->page($page)->limit($number)->select();
        $num = Db::name('refund')->where($map)->field('static,count(id) as num')->group('static')->select();
        $data['num'] = $num;
        $news_list = new News();
        $Page = $news_list->page($count, $number);
        $render = $Page->render;
        $data['count'] = $count;
        $data['data'] = $res;
        $data['render'] = $render;
        if ($res) {
            $this->_jsonp('200', '列表查询成功', $data);
        } else {
            $this->_jsonp('1000', '列表查询失败', null);
        }
    }

    public function refund_details(){
        $where['r.id']=input('get.id');
        $res=Db::name('refund')->alias('r')
            ->join('zgh_orders o','o.order=r.order','left')
            ->join('zgh_shop_information i','o.seller=i.uid','left')
            ->field('r.*,i.name')
            ->where($where)->find();

        if ($res) {
            $this->_jsonp('200', '列表查询成功', $res);
        } else {
            $this->_jsonp('1000', '列表查询失败', null);
        }
    }
	
}